package com.klhappy.houyuan.fragement;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;

import butterknife.ButterKnife;
import butterknife.InjectView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.baidu.wallet.core.utils.StringUtils;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.klhappy.houyuan.R;
import com.klhappy.houyuan.adapter.FoodsTypeAdapter;
import com.klhappy.houyuan.adapter.GoodsTypeAdapter;
import com.klhappy.houyuan.bean.BaseJsonBean;
import com.klhappy.houyuan.bean.GetGoodsBean;
import com.klhappy.houyuan.bean.GoodsNumBean;
import com.klhappy.houyuan.bean.HouYuanBean.GoodsHeadBean;
import com.klhappy.houyuan.bean.HouYuanBean.GoodsPageInfor;
import com.klhappy.houyuan.bean.HouYuanBean.GoodsRecord;
import com.klhappy.houyuan.bean.GoodsTypeBean;
import com.klhappy.houyuan.constant.UrlConstant;
import com.klhappy.houyuan.dialog.NetWorkDialog;
import com.klhappy.houyuan.interfaces.CallBackInterModle;
import com.klhappy.houyuan.activity.GoodClassActivity;
import com.klhappy.houyuan.adapter.GridViewAdapter;
import com.klhappy.houyuan.modle.HouYuanModle;
import com.klhappy.houyuan.utils.GsonRequest;
import com.klhappy.houyuan.utils.JsonCode;
import com.klhappy.houyuan.utils.NotifyMethod;
import com.klhappy.houyuan.view.AbsFragment;
import com.klhappy.houyuan.view.BaseListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Houyuan_Fragment extends AbsFragment implements CallBackInterModle {
    public static final String AVG = "Houyuan_Fragment";
    @InjectView(R.id.pull_refresh_grid)
    PullToRefreshGridView mPullRefreshGridView;
    @InjectView(R.id.iv_floatButton)
    ImageView mIvFloatButton;
    @InjectView(R.id.lift)
    LinearLayout lift_linear;
    @InjectView(R.id.right)
    LinearLayout right_linear;

    private Context mContext = null;
    private List<GoodsRecord> nowLists;
    private List<GoodsRecord> allGoods;
    private GridViewAdapter mAdapter;
    private int downPage = 1;//下一页链接
    private boolean isLoadingData = false;//
    private boolean canLoad = true;
    private GoodsHeadBean headBean;
    private List<GoodsRecord> nowGoods;
    private GoodsPageInfor pageInfor;

    private int width;
    private int height;
    private View lift;
    private View right;
    private boolean flag = true;
    private BaseListView list_types;
    private GridView right_types;
    private int clickPosition = -1;
    private List<GoodsTypeBean> goodsTypeBeans;
    private List<GoodsNumBean> goodsNumBeans;
    private HouYuanModle modle;
    private NetWorkDialog dialog;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fg1, container, false);
        ButterKnife.inject(this, view);
        mContext = getActivity();
        showDialog("请稍等...");
        dialog = new NetWorkDialog(mContext);
        allGoods = new ArrayList<GoodsRecord>();
        nowLists = new ArrayList<GoodsRecord>();
        modle = new HouYuanModle(getActivity());
        modle.setCallBackInterModle(this);
        modle.getGoodsType();
        modle.getGoods();

        mPullRefreshGridView.setMode(PullToRefreshBase.Mode.BOTH);
        mPullRefreshGridView.setOnRefreshListener(new OnRefreshListener<GridView>() {
            @Override
            public void onRefresh(PullToRefreshBase<GridView> refreshView) {
                if (!isLoadingData) {
                    if (mPullRefreshGridView.isHeaderShown()) {//刷新
                        Log.e("this", "刷新=========");
                        getData();
                    } else if (canLoad) {//加载
                        Log.e("this", "加载=========");
                        getDataDownPage();
                    } else {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                showToastx("亲,已全部加载完!");
                                mPullRefreshGridView.onRefreshComplete();
                            }
                        }, 500);
                    }
                }
            }
        });

        NotifyMethod.getInstance().addObserver(AVG, new NotifyMethod.NotifyListener() {
            @Override
            public void notify(Object o) {
                GetGoodsBean goodsBean = new GetGoodsBean();
                goodsBean.setId((String) o);
                goodsBean.setNo("1");

                JSONObject object = new JSONObject();
                JSONArray array = new JSONArray();
                try {
                    object.put("id" ,goodsBean.getId() + "");
                    object.put("no" ,goodsBean.getNo());
                    array.put(object);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                JSONObject Nobject = new JSONObject();
                try {
                    Nobject.put("goods" ,array);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                modle.setOrder(Nobject);
            }
        });

        setViewwh();
        return view;
    }

    /**
     * 分页加载 -- 下拉刷新
    * @param
    * */
    private void getData(){
        isLoadingData = true;
        String url = UrlConstant.REFRESH_URL + downPage;
        RequestQueue mRequestQueue =  Volley.newRequestQueue(getActivity());
        final Map<String ,String> params = new HashMap<>();
        GsonRequest<BaseJsonBean> gsonRequest = new GsonRequest<BaseJsonBean>
                (Request.Method.POST, url, BaseJsonBean.class , new Response.Listener<BaseJsonBean>() {
                    @Override
                    public void onResponse(BaseJsonBean o) {
                        if (o.getCode() == 200){
                            headBean = JsonCode.getClass(o.getEntity(), GoodsHeadBean.class);
                            setDownPageString(JsonCode.getClass(headBean.getPageInfor(), GoodsPageInfor.class));
                            setGoodsList(JsonCode.getClassList(headBean.getRecords(), GoodsRecord.class), true);
                        }
                        isLoadingData = false;
                        mPullRefreshGridView.onRefreshComplete();
                    }

                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        dialog.netWork("网络连接错误,请检查网络!");
                        dialog.show();
                        isLoadingData = false;
                        mPullRefreshGridView.onRefreshComplete();
                    }
                }) {

            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                //Post参数
                return params;
            }
        };

        mRequestQueue.add(gsonRequest);
    }

    private void getDataDownPage(){
        isLoadingData = true;
        String url = UrlConstant.REFRESH_URL + (downPage + 1);
        RequestQueue mRequestQueue =  Volley.newRequestQueue(getActivity());;
        final Map<String ,String> params = new HashMap<>();
        GsonRequest<BaseJsonBean> gsonRequest = new GsonRequest<BaseJsonBean>
                (Request.Method.POST, url, BaseJsonBean.class , new Response.Listener<BaseJsonBean>() {
                    @Override
                    public void onResponse(BaseJsonBean o) {
                        Gson gson = new Gson();
                        Log.e("this" , gson.toJson(o));
                        if (o.getCode() == 200){
                            headBean = JsonCode.getClass(o.getEntity(), GoodsHeadBean.class);
                            Log.e("this==" , gson.toJson(headBean));
                            setDownPageString(JsonCode.getClass(headBean.getPageInfor(), GoodsPageInfor.class));
                            setGoodsList(JsonCode.getClassList(headBean.getRecords(), GoodsRecord.class) ,false);
                        }else {
                            showToastx(o.getMsg());
                        }
                        isLoadingData = false;
                        mPullRefreshGridView.onRefreshComplete();
                    }

                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        dialog.netWork("网络连接错误,请检查网络!");
                        dialog.show();
                        isLoadingData = false;
                        mPullRefreshGridView.onRefreshComplete();
                    }
                }) {

            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                //Post参数
                return params;
            }
        };

        mRequestQueue.add(gsonRequest);
    }

    /**
     * 下一页链接处理
     *
     */
    private void setDownPageString(GoodsPageInfor pageInfor) {
        try {
            int totalPage = pageInfor.getTotalPages();
            int nowPage = pageInfor.getNowPage();
            if (nowPage < totalPage) {
                downPage = pageInfor.getNowPage();
                canLoad = true;
            }else {
                canLoad = false;
            }
        }catch (Exception e) {
            e.printStackTrace();
            canLoad = false;
        }
    }

    private void setGoodsList(List<GoodsRecord> list,boolean refresh){
        if (refresh) {
            allGoods.clear();
        }
        allGoods.addAll(list);
        nowLists.clear();
        nowLists.addAll(allGoods);

        mAdapter.setNotif(nowLists);
    }

    @Override
    public void CallBackFromModle(String url, BaseJsonBean o) {
        if (url.equals(UrlConstant.CATOGY_URL)) {
            closeDialog();
            if (o.getCode() == 200) {
                goodsTypeBeans = JsonCode.getClassList(o.getEntity(), GoodsTypeBean.class);
                if (goodsTypeBeans.size() != 0) {
                    setLift();
                    goodsNumBeans = JsonCode.getClassList(goodsTypeBeans.get(0).getChild_type(), GoodsNumBean.class);
                    if (goodsNumBeans.size() != 0) {
                        setRight();
                    }
                }
            }
        }else if (url.equals(UrlConstant.GOODS_URL)){
            if (o.getCode() == 200){
                headBean = JsonCode.getClass(o.getEntity(), GoodsHeadBean.class);
                nowGoods = JsonCode.getClassList(headBean.getRecords(), GoodsRecord.class);
                pageInfor = JsonCode.getClass(headBean.getPageInfor(), GoodsPageInfor.class);
                setView(nowGoods);
            }
        }
    }

    private void setView(List<GoodsRecord> goods){
        allGoods.addAll(goods);
        mAdapter = new GridViewAdapter(getActivity(), allGoods);
        mPullRefreshGridView.setAdapter(mAdapter);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    private void setViewwh() {
        WindowManager wm = getActivity().getWindowManager();
        width = wm.getDefaultDisplay().getWidth();
        height = wm.getDefaultDisplay().getHeight();

        lift = LayoutInflater.from(mContext).inflate(R.layout.lift_layout, null);
        right = LayoutInflater.from(mContext).inflate(R.layout.right_layout, null);

        LinearLayout.LayoutParams lf_params = new LinearLayout.LayoutParams(
                width / 3, height);
        lift.setLayoutParams(lf_params);

        LinearLayout.LayoutParams rg_params = new LinearLayout.LayoutParams(
                width * 2 / 3, height);
        right.setLayoutParams(rg_params);

        mIvFloatButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.scale);
                mIvFloatButton.startAnimation(animation);
                if (flag) {
                    mIvFloatButton.setImageResource(R.drawable.floatmenu_open);
                    lift_linear.addView(lift);
                    right_linear.addView(right);
                    flag = false;
                } else {
                    mIvFloatButton.setImageResource(R.drawable.floatmenu_close);
                    lift_linear.removeView(lift);
                    right_linear.removeView(right);
                    flag = true;
                }
            }
        });
    }

    private void setLift() {
        list_types = (BaseListView) lift.findViewById(R.id.list_types);
        final GoodsTypeAdapter adapter = new GoodsTypeAdapter(mContext, goodsTypeBeans);
        list_types.setAdapter(adapter);
        list_types.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                goodsNumBeans.clear();
                goodsNumBeans = JsonCode.getClassList(goodsTypeBeans.get(position).getChild_type(), GoodsNumBean.class);
                if (goodsNumBeans != null) {
                    setRight();
                }
                if (position != clickPosition) {
                    clickPosition = position;
                } else {
                    clickPosition = -1;
                }
                adapter.setNum(clickPosition);
                adapter.notifyDataSetChanged();
            }
        });

    }

    private void setRight() {
        right_types = (GridView) right.findViewById(R.id.grid_types);
        FoodsTypeAdapter adapter = new FoodsTypeAdapter(mContext, goodsNumBeans);
        right_types.setAdapter(adapter);
        right_types.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), GoodClassActivity.class);
                intent.putExtra("id", goodsNumBeans.get(position).getCa_id());
                intent.putExtra("name", goodsNumBeans.get(position).getCa_name());
                startActivity(intent);
            }
        });
    }

}
